
var URL=serverurl,
    pUrl;
(function($, owner) {
    owner.login = function(loginInfo, callback) {
        callback = callback || $.noop;
        loginInfo = loginInfo || {};
        loginInfo.UserName = loginInfo.UserName || '';
        loginInfo.Password = loginInfo.Password || '';
        console.log(JSON.stringify(loginInfo));
        if (loginInfo.UserName.length < 5) {
            return callback('账号最短为 5 个字符');
        }
        if (loginInfo.Password.length < 6) {
            return callback('密码最短为 6 个字符');
        }
        console.log(URL+'m=App&c=Public&a=login');
        $.ajax(URL+'m=App&c=Public&a=login',{
            data:{
                UserName:loginInfo.UserName,
                Password:loginInfo.Password
            },
            dataType:'json',
            type:'post',
            timeout:20000,
            success:function(data){
                console.log(JSON.stringify(data));
                plus.nativeUI.closeWaiting();
                if(data.status === 1){
                    return owner.createState(data.info.ID,loginInfo.UserName,data.info.TrueName,data.info.token,callback);
                }else{
                	callback(data.info);
                }
            },
            error:function(xhr,type,errorThrown){
            	console.log(type);
                plus.nativeUI.closeWaiting();
                console.log(JSON.stringify(xhr));
                callback('请求失败,请检查网络');
                //mui.toast('请求失败，请检查网络')
            }
        });
    };
    owner.createState = function(ID,UserName,TrueName,token,callback){
        var state = owner.getState();
        state.ID = ID;
        state.UserName = UserName;
        state.TrueName = TrueName;
        state.token = token;
        owner.setState(state);
        if(typeof(callback)=="function"){
            return callback();
        }
    };
    owner.getCode = function(phone,callback){
    	callback = callback || $.noop;
    	$.ajax(URL+'m=App&c=Public&a=getCode',{
            data:{
                phone:phone
            },
            dataType:'json',
            type:'post',
            timeout:20000,
            success:function(data){
                plus.nativeUI.closeWaiting();
                console.log(JSON.stringify(data));
                if(data.status === 1){
                    return callback();
                }else{
                	callback(data.info);
                }
            },
            error:function(xhr,type,errorThrown){
            	console.log(type);
                plus.nativeUI.closeWaiting();
                console.log(JSON.stringify(xhr));
                callback('请求失败,请检查网络');
                //mui.toast('请求失败，请检查网络')
            }
        });
    };
    /**
     * 重置用户密码
     * @param {Object} userInfo
     * @param {Object} callback
     */
    owner.resetPassword = function(code,password, callback){
    	callback = callback || $.noop;
    	console.log(URL+'m=App&c=Public&a=resetPassword');
    	$.ajax(URL+'m=App&c=Public&a=resetPassword',{
            data:{
                code : code,
                password : password
            },
            dataType:'json',
            type:'post',
            timeout:20000,
            success:function(data){
                plus.nativeUI.closeWaiting();
                console.log(JSON.stringify(data));
                if(data.status === 1){
                    return callback();
                }else{
                	callback(data.info);
                }
            },
            error:function(xhr,type,errorThrown){
            	console.log(type);
                plus.nativeUI.closeWaiting();
                console.log(JSON.stringify(xhr));
                callback('请求失败,请检查网络');
                //mui.toast('请求失败，请检查网络')
            }
        });
    };

    /**
     * 新用户注册
     **/
    owner.reg = function(regInfo, callback) {
        callback = callback || $.noop;
        regInfo = regInfo || {};
        regInfo.UserName = regInfo.UserName.replace(/^\s+|\s+$/gm,'') || '';
        regInfo.Phone = regInfo.Phone.replace(/^\s+|\s+$/gm,'') || '';
        regInfo.Password = regInfo.Password.replace(/^\s+|\s+$/gm,'') || '';

        if(regInfo.UserName.length < 2){
            return callback('用户名不能少于2个字符');
        }
        if (regInfo.Password.length < 6) {
            return callback('密码最短需要 6 个字符');
        }
        if (!checkPhone(regInfo.Phone)) {
            return callback('手机号不正确！');
        }
        plus.nativeUI.showWaiting('用户注册中...',{padlock:true});

        $.ajax(URL+'g=Admin&m=Public&a=doRegister&app=true',{
            data:{
                UserName:regInfo.UserName,
                Password:regInfo.Password,
                Phone:regInfo.Phone
            },
            dataType:'json',
            type:'post',
            timeout:20000,
            success:function(data){
                ///console.log('123');
                console.log(JSON.stringify(data));
                plus.nativeUI.closeWaiting();
                if(data.TrueName){
                    return owner.createState(data.ID,regInfo.UserName,data.TrueName,data.token,callback);
                }else{
                    mui.toast(data.info)
                }
            },
            error:function(xhr,type,errorThrown){
                console.log(URL);
                plus.nativeUI.closeWaiting();
                console.log(JSON.stringify(xhr))
                mui.toast('请求失败，请检查网络')
            }
        });
        //return callback();
    };
    
    owner.logout = function(callback){
    	$.ajax(URL+'m=App&c=Public&a=logout',{
            data:{},
            dataType:'json',
            type:'post',
            timeout:20000,
            success:function(data){
                console.log(JSON.stringify(data));
                plus.nativeUI.closeWaiting();
                if(data.status === 1){
                    return owner.createState(data.info.ID,loginInfo.UserName,data.info.TrueName,data.info.token,callback);
                }else{
                	callback(data.info);
                }
            },
            error:function(xhr,type,errorThrown){
            	console.log(type);
                plus.nativeUI.closeWaiting();
                console.log(JSON.stringify(xhr));
                callback('请求失败,请检查网络');
                //mui.toast('请求失败，请检查网络')
            }
        });
    };

    owner.reset = function(phone,callback){
        if (!checkPhone(phone)) {
            console.log(phone);
            return callback('手机号不正确！');
        }
        $.ajax(URL+'g=Admin&m=Public&a=sendSms',{
            data:{
                phone:phone
            },
            dataType:'json',
            type:'post',
            timeout:20000,
            success:function(data){
                ///console.log('123');
                console.log(JSON.stringify(data));
                plus.nativeUI.closeWaiting();
                if(typeof(callback)=="function"){
                    if(data.state == 'fail'){
                        return callback(data.info);
                    }else{
                        return callback();
                    }
                }
            },
            error:function(xhr,type,errorThrown){
                console.log(URL);
                plus.nativeUI.closeWaiting();
                console.log(JSON.stringify(xhr))
                mui.toast('请求失败，请检查网络')
            }
        });
    };

    /**
     * 获取当前状态
     **/
    owner.getState = function() {
        var stateText = localStorage.getItem('$state') || "{}";
        return JSON.parse(stateText);
    };

    /**
     * 设置当前状态
     **/
    owner.setState = function(state) {
        state = state || {};
        localStorage.setItem('$state', JSON.stringify(state));
    };

    var checkEmail = function(email) {
        email = email || '';
        return (email.length > 3 && email.indexOf('@') > -1);
    };

    var checkPhone = function(inputString){
        var partten = /^1[3,5,7,8]\d{9}$/;
        if(partten.test(inputString)){
            return true;
        }else{
            return false;
        }
    }
    /**
     * 找回密码
     **/
    owner.forgetPassword = function(email, callback) {
        callback = callback || $.noop;
        if (!checkEmail(email)) {
            return callback('邮箱地址不合法');
        }
        return callback(null, '暂不支持邮箱找回密码功能，请前往PC端找回密码' /*'新的随机密码已经发送到您的邮箱，请查收邮件。'*/);
    };

    /**
     * 设置应用本地配置
     **/
    owner.setSettings = function(settings) {
        settings = settings || {};
        localStorage.setItem('$settings', JSON.stringify(settings));
    }

    /**
     * 获取应用本地配置
     **/
    owner.getSettings = function() {
        var settingsText = localStorage.getItem('$settings') || "{}";
        return JSON.parse(settingsText);
    }

    //判断是否是ios
    owner.ios = function() {
        if (plus.os.name.toLocaleLowerCase() == 'ios') {
            return true;
        } else {
            return false;
        }
    };
    /**
     * 获取本地是否安装客户端
     **/
    owner.isInstalled = function(id) {
        if (id === 'qihoo' && mui.os.plus) {
            return true;
        }
        if (mui.os.android) {
            var main = plus.android.runtimeMainActivity();
            var packageManager = main.getPackageManager();
            var PackageManager = plus.android.importClass(packageManager)
            var packageName = {
                "qq": "com.tencent.mobileqq",
                "weixin": "com.tencent.mm",
                "sinaweibo": "com.sina.weibo"
            }
            try {
                return packageManager.getPackageInfo(packageName[id], PackageManager.GET_ACTIVITIES);
            } catch (e) {}
        } else {
            switch (id) {
                case "qq":
                    var TencentOAuth = plus.ios.import("TencentOAuth");
                    return TencentOAuth.iphoneQQInstalled();
                case "weixin":
                    var WXApi = plus.ios.import("WXApi");
                    return WXApi.isWXAppInstalled()
                case "sinaweibo":
                    var SinaAPI = plus.ios.import("WeiboSDK");
                    return SinaAPI.isWeiboAppInstalled()
                default:
                    break;
            }
        }
    }
    //IOS判断QQ是否已经安装
    owner.isQQInstalled = function() {
        var TencentOAuth = plus.ios.import("TencentOAuth");
        var isQQInstalled = TencentOAuth.iphoneQQInstalled();
        return isQQInstalled == '0' ? false : true
    };
    //IOS判断微信是否已经安装
    owner.isWXInstalled = function() {
        var Weixin = plus.ios.import("WXApi");
        var isWXInstalled = Weixin.isWXAppInstalled();
        return isWXInstalled == '0' ? false : true;
    };

    /*大于零显示元素*/
    owner.whichShow = function(data,obj) {
        if(data>0){
            document.getElementById(obj).innerText=data.toString();
            document.getElementById(obj).style.display='block';
        }else{
            document.getElementById(obj).style.display='none';
        }

    }

    /*不为空显示*/
    owner.nullShow = function(data,obj) {
        if(data!=''&&data!=null){
            document.getElementById(obj).innerText=data;
            document.getElementById(obj).style.display='block';
        }else{
            document.getElementById(obj).style.display='none';
        }

    }

    //阻止a链接跳转
    owner.stopHref = function(obj) {
        obj.on('tap', 'a', function(e) {
            e.preventDefault();
        });
    }

    owner.trim = function(str) {
        return str.replace(/(^\s*)|(\s*$)/g, "");
    }

    owner.isLogin = function(){
        var userState = JSON.parse(localStorage.getItem('$state') || "{}");
        if (userState.ID && userState.ID != '') {
            return true;
        } else {
            return false;
        }
    }
    //打开软键盘
    owner.openSoftKeyboard = function() {
        if (mui.os.ios) {
            var webView = plus.webview.currentWebview().nativeInstanceObject();
            webView.plusCallMethod({
                "setKeyboardDisplayRequiresUserAction": false
            });
        } else {
            var webview = plus.android.currentWebview();
            plus.android.importClass(webview);
            webview.requestFocus();
            var Context = plus.android.importClass("android.content.Context");
            var InputMethodManager = plus.android.importClass("android.view.inputmethod.InputMethodManager");
            var main = plus.android.runtimeMainActivity();
            var imm = main.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
        }
    };
}(mui, window.app = {}));

